package com.me.service;

import com.me.pojo.PhoneCode;
import com.me.util.UserContext;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("verifyCodeService")
public class VerifyCodeServiceImpl implements VerifyCodeService {


    @Test
    public Integer send(String phone){
      /*
         1.用户点击发送验证码
         2.验证用户手机号是否为注册用户
         3.生成验证码，并且绑定此手机号(cookie session sql)
         4.发送验证码
         5.用户接收到验证码，输入验证码，点击登录
         6.后台服务验证用户的手机号和验证码是否匹配，如果匹配登录成功，否则登录失败
       */
        int mobile_code = (int)((Math.random() * 9 + 1) * 100000); // 生成符合规范的随机数
        String content = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";
        // 添加参数
        HashMap<String, String> params = new HashMap<>();
        params.put("account","C83434898");                              //APIID
        params.put("password","aaea0e85df46c08fb6ea35c7b1899564");    //APIKEY
        params.put("mobile","15228607864");                             // 发送给哪一个手机号
        params.put("content",content);                                   // 发送的内容

        // 实例化HTTP方法
        HttpPost request = new HttpPost();
        // 封装请求地址
        try {
            request.setURI(new URI("https://106.ihuyi.com/webservice/sms.php?method=Submit"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // 设置参数
        List<NameValuePair> nameValuePairsList = new ArrayList<>();
        // 封装数据值
        for (String name : params.keySet()) {
            String value = params.get(name);
            nameValuePairsList.add(new BasicNameValuePair(name, value));
        }
        HttpClient client = new DefaultHttpClient();//客户端
        try {
            request.setEntity(new UrlEncodedFormEntity(nameValuePairsList, HTTP.UTF_8));
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){ //200代表成功
                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuilder sb = new StringBuilder("");
                String line = "";
                String NL = System.getProperty("line.separator");   // 回车使用line.separator(回车)
                while ((line = in.readLine()) != null) {
                    sb.append(line).append(NL);    // 每添加一个值追加一个回车
                }
                in.close();
                String SubmitResult = sb.toString();
                System.out.println("服务器返回结果内容：" + SubmitResult);
                // 解析XML文件   Document XML文件对象
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                String code = root.elementText("code");
                String msg = root.elementText("msg");
                String smsid = root.elementText("smsid");

                System.out.println("回执状态码：" + code);
                System.out.println("回执消息：" + msg);
                System.out.println("回执ID：" + smsid);
                System.out.println("信息：" + mobile_code);
                if("2".equals(code)){
                    System.out.println("短信提交成功");
                    return mobile_code;
                }
                return mobile_code;
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally{
            // Release connection
            request.releaseConnection();
            client.getConnectionManager().shutdown();
        }
        return  null;
    }

    /**
     * 发送手机验证 调用send方法 将验证码存入session中
     * @param phoneNumber 手机号。
     */
    @Override
    public void sendVerifyCode(String phoneNumber) {
        PhoneCode codePhone=new PhoneCode();
        Integer send = this.send(phoneNumber);//发送的验证码
        codePhone.setPhoneNumber(phoneNumber);
        codePhone.setCode(String.valueOf(send));
        Date date=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        codePhone.setSendTime(dateFormat.format(date));
        UserContext.putVerifyCode(codePhone);//将短信验证的有关信息存在session中。
        System.out.println(UserContext.getVerifyCode().getPhoneNumber());
    }

    /**
     * 将存在session中的手机号和验证码进行验证。
     * @param phoneNumber 手机号
     * @param verifyCode 验证码
     * @return  boolean是否一样
     */
    @Override
    public boolean validate(String phoneNumber, String verifyCode) {
        PhoneCode code = UserContext.getVerifyCode();
        String code1=code.getCode();
        String  phone1=code.getPhoneNumber();//获取session中的手机号和验证码
        System.out.println("信息得到中....."+code1+" "+verifyCode+" "+phone1+" "+phoneNumber);
        if(code1.equals(verifyCode))
        {
            if(phone1.contains(phoneNumber))
                return true;
            else
                return  false;
        }
        else
            return false;
    }

}
